import { http } from '@/utils/request';
import type { HttpResponse } from '@/utils/request';

// ==================== 类型定义 ====================

/**
 * 产品信息
 */
export interface ProductInfo {
  productId?: string;
  productName?: string;
  productPriceStart?: string;
  productPriceEnd?: string;
}

/**
 * 身份证识别结果
 */
export interface IdCardOcrResult {
  name?: string;
  sex?: string;
  ethnicity?: string;
  birthDate?: string;
  address?: string;
  idNumber?: string;
}

/**
 * 驾驶证识别结果
 */
export interface DrivingLicenseOcrResult {
  name?: string;
  sex?: string;
  nationality?: string;
  birthDate?: string;
  address?: string;
  licenseNumber?: string;
  initialIssueDate?: string;
  approvedType?: string;
  issueAuthority?: string;
  validFromDate?: string;
  validPeriod?: string;
}

/**
 * 行驶证识别结果
 */
export interface VehicleLicenseOcrResult {
  licensePlateNumber?: string;
  inspectionRecord?: string;
  passengerCapacity?: string;
  totalWeight?: string;
  curbWeight?: string;
  permittedWeight?: string;
  overallDimension?: string;
  tractionWeight?: string;
  energySign?: string;
  recordNumber?: string;
  remarks?: string;
  barcodeNumber?: string;
  vehicleType?: string;
  owner?: string;
  address?: string;
  useNature?: string;
  model?: string;
  vinCode?: string;
  engineNumber?: string;
  registrationDate?: string;
  issueDate?: string;
  issueAuthority?: string;
}

/**
 * 创建订单请求参数
 */
export interface CreateOrderPayload {
  productId: string;
  payChannel: string; // 支付渠道：00线上 01线下
  payMethod?: string; // 支付方式：00微信 01支付宝 02线下自结 03POS机支付 04对公转账
  payType: string; // 支付类型：00全款 01定金
  totalAmount: number;
  depositAmount?: number;
  idType?: string; // 证件类型：00身份证 01驾驶证
  customName: string;
  customIdCard?: string;
  customPhone: string;
}

/**
 * 创建订单响应
 */
export interface CreateOrderResult {
  orderId: string;
  payId: string;
}

/**
 * 修改订单请求参数
 */
export interface UpdateOrderPayload {
  orderId: string;
  idType?: string;
  customName: string;
  customIdCard: string;
  customPhone: string;
  customEmail?: string;
  fileList?: string[];
  vinCode: string;
  engineNumber: string;
  licensePlateNumber?: string;
  vehicleType: string;
  model: string;
  useNature: string;
  passengerCapacity?: string;
  carPrice: number;
  payCarTime: string;
  otherMessage?: string;
  insuranceNo?: string;
  insuranceStartTime?: string;
  insuranceEndTime?: string;
  insuranceCompany?: string;
}

/**
 * 订单列表请求参数
 */
export interface OrderListParams {
  pageSize?: number;
  pageNum?: number;
}

/**
 * 订单列表项
 */
export interface OrderListItem {
  orderId?: string;
  productName?: string;
  customName?: string;
  customIdCard?: string;
  customPhone?: string;
  orderTime?: string;
  orderStatus?: string; // 支付状态：00待支付 01支付成功 02已取消
  orderStatusName?: string;
  supplementStatus?: string; // 补录状态：00未补录 01已补录
}

/**
 * 订单列表响应
 */
export interface OrderListResult {
  list?: OrderListItem[];
  total?: number;
}

/**
 * 支付信息
 */
export interface OrderPayInfo {
  payId?: string;
  orderId?: string;
  totalAmount?: number;
  paidAmount?: number;
  discountAmount?: number;
  unpaidAmount?: number;
  payNo?: string;
  payType?: string; // 支付类型：00全款 01定金 02尾款
  payTypeName?: string;
  payMethod?: string; // 支付方式：00微信 01支付宝 02线下自结 03POS机支付 04对公转账
  payMethodName?: string;
  payChannel?: string; // 支付渠道：00线上 01线下
  payChannelName?: string;
  payStatus?: string; // 支付状态：00待支付 01支付成功 02已取消
  payStatusName?: string;
  paidTime?: string;
  cancelTime?: string;
  qrCodeUrl?: string; // 支付二维码地址（如有）
}

/**
 * 订单详情
 */
export interface OrderDetail {
  orderId?: string;
  orderNo?: string;
  productName?: string;
  distributorName?: string;
  orderTime?: string;
  totalAmount?: number;
  paidAmount?: number;
  discountAmount?: number;
  unpaidAmount?: number;
  orderStatus?: string;
  orderStatusName?: string;
  supplementStatus?: string; // 补录状态：00未补录 01已补录
  reviewStatus?: string;
  reviewStatusName?: string;
  idType?: string;
  idTypeName?: string;
  customName?: string;
  customIdCard?: string;
  customPhone?: string;
  customEmail?: string;
  payInfoList?: OrderPayInfo[];
  vinCode?: string;
  engineNumber?: string;
  licensePlateNumber?: string;
  vehicleType?: string;
  model?: string;
  useNature?: string;
  passengerCapacity?: string;
  carPrice?: number;
  payCarTime?: string;
  otherMessage?: string;
  insuranceNo?: string;
  insuranceStartTime?: string;
  insuranceEndTime?: string;
  insuranceCompany?: string;
  fileList?: string[];
}

/**
 * 订单补录请求参数（暂存和提交共用）
 */
export interface OrderSupplementPayload {
  orderId: string;
  idType?: string;
  customName: string;
  customIdCard: string;
  customPhone: string;
  customEmail?: string;
  fileList?: string[];
  vinCode: string;
  engineNumber: string;
  licensePlateNumber?: string;
  vehicleType: string;
  model: string;
  useNature: string;
  passengerCapacity?: string;
  carPrice: number;
  payCarTime: string;
  otherMessage?: string;
  insuranceNo?: string;
  insuranceStartTime?: string;
  insuranceEndTime?: string;
  insuranceCompany?: string;
}

/**
 * 支付剩余金额请求参数
 */
export interface CreateLeftAmountOrderPayload {
  orderId: string;
  payChannel: string; // 支付渠道：00线上 01线下
  payMethod?: string; // 支付方式：00微信 01支付宝 02线下自结 03POS机支付 04对公转账
  paidAmount: number;
}

/**
 * 支付剩余金额响应
 */
export interface CreateLeftAmountOrderResult {
  payId: string;
}

/**
 * 支付取消请求参数
 */
export interface CancelPayPayload {
  payId: string;
}

// ==================== API 接口 ====================

/**
 * 产品选择
 */
export async function fetchProductSelect(): Promise<ProductInfo[]> {
  const response = await http.post<ProductInfo[]>('/product/select');
  return (response.data as ProductInfo[]) || [];
}

/**
 * 身份证识别
 */
export async function idCardOcr(url: string): Promise<IdCardOcrResult | null> {
  const response = await http.post<IdCardOcrResult>('/order/idCardOcr', { url });
  return (response.data as IdCardOcrResult) || null;
}

/**
 * 驾驶证识别
 */
export async function drivingLicenseOcr(url: string): Promise<DrivingLicenseOcrResult | null> {
  const response = await http.post<DrivingLicenseOcrResult>('/order/drivingLicenseOcr', { url });
  return (response.data as DrivingLicenseOcrResult) || null;
}

/**
 * 行驶证识别
 */
export async function vehicleLicenseOcr(url: string): Promise<VehicleLicenseOcrResult | null> {
  const response = await http.post<VehicleLicenseOcrResult>('/order/vehicleLicenseOcr', { url });
  return (response.data as VehicleLicenseOcrResult) || null;
}

/**
 * 创建订单
 */
export async function createOrder(payload: CreateOrderPayload): Promise<CreateOrderResult | null> {
  const response = await http.post<CreateOrderResult>('/order/createOrder', payload);
  return (response as CreateOrderResult) || null;
}

/**
 * 修改订单
 */
export async function updateOrder(payload: UpdateOrderPayload): Promise<HttpResponse<null>> {
  return http.post<null>('/order/updateOrder', payload);
}

/**
 * 订单列表
 */
export async function fetchOrderList(params?: OrderListParams): Promise<OrderListResult> {
  return await http.post<OrderListResult>('/order/list', params);
}

/**
 * 订单详情
 */
export async function fetchOrderDetail(orderId: string): Promise<OrderDetail | null> {
  const response = await http.post<OrderDetail>('/order/info', { orderId });
  return (response as OrderDetail) || null;
}

/**
 * 订单补录暂存
 */
export async function tempStorageOrderSupplement(payload: OrderSupplementPayload): Promise<HttpResponse<null>> {
  return http.post<null>('/order/supplement/tempStorage', payload);
}

/**
 * 订单补录提交
 */
export async function submitOrderSupplement(payload: OrderSupplementPayload): Promise<HttpResponse<null>> {
  return http.post<null>('/order/supplement/submit', payload);
}

/**
 * 根据原始订单支付剩余金额
 */
export async function createLeftAmountOrder(
  payload: CreateLeftAmountOrderPayload,
): Promise<CreateLeftAmountOrderResult | null> {
  const response = await http.post<CreateLeftAmountOrderResult>('/order/leftAmount/createOrder', payload);
  return (response as CreateLeftAmountOrderResult) || null;
}

/**
 * 代理商订单支付记录详情
 */
export async function fetchPayInfo(payId: string): Promise<OrderPayInfo | null> {
  const response = await http.post<OrderPayInfo>('/order/pay/info', { payId });
  return (response as OrderPayInfo) || null;
}

/**
 * 代理商订单支付取消
 */
export async function cancelPay(payload: CancelPayPayload): Promise<HttpResponse<null>> {
  return http.post<null>('/order/pay/cancel', payload);
}

